package cn.iocoder.yudao.module.handguard.job;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.handguard.dal.dataobject.housingresource.HousingResourceDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.housingresource.HousingResourceMapper;
import com.lw.reptiles.dto.HouseTags;
import com.lw.reptiles.dto.JsonResult;
import com.lw.reptiles.dto.PageData;
import com.lw.reptiles.dto.ReptilesDto;
import com.lw.reptiles.service.ReptilesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@Component
@Slf4j
public class ScheduledTwoTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    // 最大重试次数
    private static final int MAX_RETRIES = 3;

    // 每次重试之间的等待时间（秒）
    private static final int RETRY_DELAY = 2;

    @Resource
    private HousingResourceMapper housingResourceMapper;




    //住宅-同步数据
    @Scheduled(cron = "10 19 18 * * ?")
    //@Scheduled(cron = "0 30 */2 * * ?") //每两小时30分执行一次
    @Transactional
    public void sysResidenceHousing() {
        log.info("开始同步");
        List<HousingResourceDO> checkList = new ArrayList<>();
        //获取页数
        JsonResult jsonResult = ReptilesService.getHousingData(1, 10, "重庆市");
        if (jsonResult.getCode() == 200) {
            PageData pageData = (PageData) jsonResult.getData();
            int totalCount = pageData.getTotal(); // 总条数
            int pageSize = 10;    // 每页条数
            int totalPages = calculateTotalPages(totalCount, pageSize);
            //String url =  housingResourceMapper.getSslURL("ssl.image.url");;
            //遍历所有数据
            for (int i = 0; i < totalPages; i++) {
                JsonResult result = ReptilesService.getHousingData(i + 1, 10, "重庆市");
                PageData resultData = (PageData) result.getData();
                if (resultData.getRows() != null) {
                    List<ReptilesDto> rows = resultData.getRows();
                    List<HousingResourceDO> doList = format(rows,1);
                    //housingResourceMapper.saveOrUpdateBatch(doList);
                    checkList.addAll(doList);
                }
                try {
                    //log.info("1秒一次");
                    TimeUnit.SECONDS.sleep(1); // 添加1秒的延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for(HousingResourceDO resourceDO: checkList){
                HousingResourceDO housingResourceDO =  housingResourceMapper.selectById(resourceDO.getId());
                if (housingResourceDO!=null){
                    housingResourceMapper.updateById(resourceDO);
                }else {
                    //可能存在deleted被标记删除的数据，先删除
                    housingResourceMapper.deleteByHousingId(resourceDO.getId());
                    if (resourceDO.getId()==267315l || resourceDO.getId()==267224l ){
                    }else {
                        housingResourceMapper.insert(resourceDO);
                    }
                }
            }

            //数据校对，如果我们这边存在旧数据，另一边没有，就物理删除
            LambdaQueryWrapperX<HousingResourceDO> wrapperX  = new LambdaQueryWrapperX<>();
            wrapperX.eq(HousingResourceDO::getIsHutai,"0");
            wrapperX.eq(HousingResourceDO::getHousingType,1);
            List<HousingResourceDO> housingList = housingResourceMapper.selectList(wrapperX);
            for (HousingResourceDO d : housingList){
                if (StringUtils.isEmpty(d.getCreator())){
                    boolean exists = checkList.stream().anyMatch(data -> data.getId().equals(d.getId()));
                    if (!exists){
                        housingResourceMapper.deleteById(d.getId());
                    }
                }
                //System.out.println("ID " + id + " exists in list2: " + exists);
            }

        }
        log.info("房源信息同步完成");
    }



    //========================================商业===========================================




    @Scheduled(cron = "10 35 18 * * ?")
    @Transactional
    public void sysBusinessHousing() {
        log.info("开始同步");
        List<HousingResourceDO> checkList = new ArrayList<>();
        //获取页数
        JsonResult jsonResult = ReptilesService.getHousingShangYeData(1, 10, "重庆市");
        if (jsonResult.getCode() == 200) {
            PageData pageData = (PageData) jsonResult.getData();
            int totalCount = pageData.getTotal(); // 总条数
            int pageSize = 10; // 每页条数
            int totalPages = calculateTotalPages(totalCount, pageSize);
            //String url =  housingResourceMapper.getSslURL("ssl.image.url");;
            //遍历所有数据
            for (int i = 0; i < totalPages; i++) {
                JsonResult result = ReptilesService.getHousingShangYeData(i + 1, 10, "重庆市");
                PageData resultData = (PageData) result.getData();
                if (resultData.getRows() != null) {
                    List<ReptilesDto> rows = resultData.getRows();
                    List<HousingResourceDO> doList = format(rows,2);
                    //housingResourceMapper.saveOrUpdateBatch(doList);
                    checkList.addAll(doList);
                }
                try {
                    //log.info("1秒一次");
                    TimeUnit.SECONDS.sleep(1); // 添加1秒的延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for(HousingResourceDO resourceDO: checkList){
                HousingResourceDO housingResourceDO =  housingResourceMapper.selectById(resourceDO.getId());
                if (housingResourceDO!=null){
                    housingResourceMapper.updateById(resourceDO);
                }else {
                    //可能存在deleted被标记删除的数据，先删除
                    housingResourceMapper.deleteByHousingId(resourceDO.getId());
                    if (resourceDO.getId()==267315l  || resourceDO.getId()==267224l ){
                    }else {
                        housingResourceMapper.insert(resourceDO);
                    }
                }
            }

            //数据校对，如果我们这边存在旧数据，另一边没有，就物理删除
            LambdaQueryWrapperX<HousingResourceDO> wrapperX  = new LambdaQueryWrapperX<>();
            wrapperX.eq(HousingResourceDO::getIsHutai,"0");
            wrapperX.eq(HousingResourceDO::getHousingType,2);
            List<HousingResourceDO> housingList = housingResourceMapper.selectList(wrapperX);
            for (HousingResourceDO d : housingList){
                if (StringUtils.isEmpty(d.getCreator())){
                    boolean exists = checkList.stream().anyMatch(data -> data.getId().equals(d.getId()));
                    if (!exists){
                        housingResourceMapper.deleteById(d.getId());
                    }
                }
                //System.out.println("ID " + id + " exists in list2: " + exists);
            }

        }
        log.info("商业房源信息同步完成");
    }

    private List<HousingResourceDO> format(List<ReptilesDto> rows,Integer housingType){
        //log.info("进来了");
        List<HousingResourceDO> voList = new ArrayList<>();
        for (ReptilesDto vo : rows) {

            HousingResourceDO resourceDO = new HousingResourceDO();
            resourceDO.setTitle(vo.getTitle());
            resourceDO.setArea(String.valueOf(vo.getArea()));
            resourceDO.setHouseType(vo.getLayout());
            resourceDO.setHousingType(housingType);
            if (vo.getAuctionMode().equals("1")) {
                resourceDO.setAuctionNumber("一拍");//拍卖方式
            } else if (vo.getAuctionMode().equals("2")) {
                resourceDO.setAuctionNumber("二拍");//拍卖方式
            } else if (vo.getAuctionMode().equals("3")) {
                resourceDO.setAuctionNumber("变卖");//拍卖方式
            } else if (vo.getAuctionMode().equals("4")) {
                resourceDO.setAuctionNumber("其他");//拍卖方式
            }else {
                resourceDO.setAuctionNumber("其他");//拍卖方式
            }
            resourceDO.setMarketPrice(String.valueOf(vo.getMarketPrice()));

            //DecimalFormat df = new DecimalFormat("#.00");
            //String scdj = df.format(vo.getScdj());
            resourceDO.setMarketUnitPrice(String.valueOf(vo.getScdj()));//市场单价
            //String jlkj = df.format(vo.getJlkj());
            resourceDO.setPickupSpacePrice(String.valueOf(vo.getJlkj()));//捡漏空间
            resourceDO.setStartingOddPrice(String.valueOf(vo.getStartingUnitPrice()));
            resourceDO.setStartingPrice(String.valueOf(vo.getStartingPrice()));

            if (resourceDO.getStartingOddPrice().equals("null")){
                resourceDO.setStartingOddPrice("");
            }

            if (vo.getHouseTagsList() != null && vo.getHouseTagsList().size() > 0) {
                HouseTags houseTags = vo.getHouseTagsList().get(0);
                if (houseTags!=null){
                    if (StringUtils.isNotEmpty(houseTags.getTagName())){
                        resourceDO.setDiscount(houseTags.getTagName());
                    }
                }
            }
            resourceDO.setCellName(vo.getCommunityName());
            if (StringUtils.isNotEmpty(vo.getElevator())) {
                if (vo.getElevator().equals("1")) {
                    resourceDO.setStep("电梯");//梯步
                } else if (vo.getElevator().equals("2")) {
                    resourceDO.setStep("楼梯");//梯步
                }else if (vo.getElevator().equals("3")) {
                    resourceDO.setStep("未知");//未知
                }
            } else {
                resourceDO.setStep("未知");//梯步
            }


            resourceDO.setFloor(vo.getFloorLevel());
            if (StringUtils.isNotEmpty(vo.getPropertyType())) {
                if (vo.getPropertyType().equals("1")) {
                    resourceDO.setPropertyType("高层");
                } else if (vo.getPropertyType().equals("2")) {
                    resourceDO.setPropertyType("中层");
                } else if (vo.getPropertyType().equals("3")) {
                    resourceDO.setPropertyType("低层");
                }else {
                    resourceDO.setPropertyType("未知");
                }
//                else if (resourceDO.getPropertyType().equals("null")){
//                    resourceDO.setPropertyType("");
//                }
            } else {
                resourceDO.setPropertyType("未知");
            }

            if (StringUtils.isNotEmpty(resourceDO.getArea())){
                if (resourceDO.getArea().equals("null")){
                    resourceDO.setArea("");
                }
            }

            if (StringUtils.isNotEmpty(resourceDO.getFloor())){
                if (resourceDO.getFloor().equals("null")){
                    resourceDO.setFloor("");
                }
            }

            resourceDO.setNumberOfAuctions(Integer.valueOf(vo.getAuctionMode()));
            resourceDO.setEarnestMoney(String.valueOf(vo.getGuaranteeAmount()));
            resourceDO.setBidIncrement(String.valueOf(vo.getMarkupPrice()));
            resourceDO.setDiscountRate(String.valueOf(vo.getZkl()));//折扣率
            resourceDO.setArchitectureYear(String.valueOf(vo.getBuildYear()));//建筑年份
            if (resourceDO.getArchitectureYear().equals("null")){
                resourceDO.setStartingOddPrice("");
            }

            //装修情况
            if (vo.getDecoration().equals("1")){
                resourceDO.setDecorateSituation("装修");
            }else if (vo.getDecoration().equals("2")){
                resourceDO.setDecorateSituation("清水");
            }else if (vo.getDecoration().equals("3")){
                resourceDO.setDecorateSituation("未知");
            }
            resourceDO.setAddress(vo.getAddress());

            String data = vo.getLocation();
            String[] parts = data.split(",");
            // 逗号前的数据
            String before = parts[0];
            // 逗号后的数据
            String after = parts.length > 1 ? parts[1] : "";
            resourceDO.setLatitude(after);
            resourceDO.setLongitude(before);
            resourceDO.setAuctionState(vo.getStatus());
            resourceDO.setAuctionTime(vo.getAuctionTime());
            //resourceDO.setCreateTime(new Date());

            //图片处理
            String[] detailPicArr = vo.getDetailPic().split(",");
            String detailPic = "";
            for (String c : detailPicArr) {
                String imgUrl = c;
                int lastCommaIndex = imgUrl.lastIndexOf("/");
                if (lastCommaIndex != -1) {
                    String result = imgUrl.substring(lastCommaIndex + 1);
                    String newUrl = "/detailPic/" + result;
                    detailPic += newUrl + ",";
                } else {
                    //System.out.println("没有逗号");
                }
            }
            resourceDO.setDetailPic(detailPic);

            //图片处理
            String[] coverPicArr = vo.getCoverPic().split(",");
            String coverPic = "";
            for (String c : coverPicArr) {
                String imgUrl = c;
                int lastCommaIndex = imgUrl.lastIndexOf("/");
                if (lastCommaIndex != -1) {
                    String result = imgUrl.substring(lastCommaIndex + 1);
                    String newUrl = "/coverPic/" + result;
                    coverPic += newUrl + ",";
                } else {
                    //System.out.println("没有逗号");
                }
            }
            resourceDO.setCoverPic(coverPic);


            if (StringUtils.isNotEmpty(vo.getInfoTable())) {
                String bgImg = vo.getBackgroundPic();
                int lastCommaIndex = bgImg.lastIndexOf("/");
                if (lastCommaIndex != -1) {
                    String result = bgImg.substring(lastCommaIndex + 1);
                    String newUrl = "/backgroundPic/" + result;
                    resourceDO.setBackgroundPic(newUrl);
                } else {
                    //System.out.println("没有逗号");
                }
            }

            if (StringUtils.isNotEmpty(vo.getInfoTable())) {
                String intoTableImg = vo.getInfoTable();
                int intoLastCommaIndex = intoTableImg.lastIndexOf("/");
                if (intoLastCommaIndex != -1) {
                    String result = intoTableImg.substring(intoLastCommaIndex + 1);
                    String newUrl = "/intoTable/" + result;
                    resourceDO.setInfoTable(newUrl);
                } else {
                    //System.out.println("没有逗号");
                }
            }

            resourceDO.setId(Long.valueOf(vo.getId()));
            voList.add(resourceDO);
        }

        return voList;
    }

    public static int calculateTotalPages(int totalCount, int pageSize) {
        if (pageSize <= 0) {
            throw new IllegalArgumentException("Page size must be greater than zero.");
        }
        return (totalCount + pageSize - 1) / pageSize;
    }


    //每天更新竞拍状态
//    @Scheduled(cron = "20 16 09 * * ?")
//    public void updateAuctionState(){
//
//    }

}